
#-*- coding: UTF-8 -*-

'''
Created on Mar 7, 2011

@author: Juho Salmio
'''

import urllib2
from BeautifulSoup import BeautifulSoup as Soup
import difflib
import sys
import os.path
'''
Reads the lastsong file, sends requests according to the data and parses the
results to a clean string and prints the result

'''
path = os.path.dirname(sys.argv[0])

def main():
    
    
    src = open(os.path.expanduser('~/Library/Logs/lastsong'), 'r')
    text = src.read()
    src.close()
    split = text.split('@')
    artist = split[1]
    song = split[0]

    print parseChartLyricsUrl(artist, song)


def parseChartLyricsUrl(artist, song):    
    
    split = song.split("(")
    split1 = split[0].split('[')
    split2 = split1[0].split('-')
    song = split2[0]
    song = song[:20]
    song = song.strip()
    puresong = song
    
    song = song.replace(" ","%20")
    artist = artist[:20]
    artist  = artist.replace('\n','')
    artist = artist.replace(' ','%20')
    
    
    url = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyric?artist=%s&song=%s'%(artist,song)
   
    #print url
    
    
    try:
        dest = open(os.path.expanduser('~/Library/Logs/songurl'),"w")
        req = urllib2.Request(url)
        page = urllib2.urlopen(req).read()
        
        soup = Soup(page)
        
        
        '''
        The searchresult-xml file is in popularity order so we have to find
        the right song from there.
        Let's find all <songtags> from page and find the songname which is 
        closest to ours
        '''
        songurls =soup.findAll('songurl')
        if len(songurls) == 0:
            return 'No content'
        
        
        songtags = soup.findAll('song')
       
        bestindx = 0
        bestratio = 0
        for indx, songtag in enumerate(songtags):
            split = songtag.string.split('(')
            songtag = split[0]
            ratio = difflib.SequenceMatcher(None,songtag.lower(),
                                                    puresong.lower()).ratio()
            
            if ratio > bestratio:
                bestratio = ratio
                bestindx = indx
       
        
        #Now we know the the index to the songurl
        
        songurl = songurls[bestindx].string
       
        
        req2 = urllib2.Request(songurl)
        page2 = urllib2.urlopen(req2).read()
        
        # because we would like to show the sourceurl in the widget
        dest.write(songurl)
        
        
        
    except urllib2.HTTPError:
      
        dest.write("")
        return 'No Content'
    
    dest.close()
    
    #Let's remove the junk
    ptag = page2[page2.find('<p>')+3:page2.find('</p>')]
    
    ptag = ptag.replace('<br /> <br />','\n')
    ptag = ptag.replace('<br />','')
    parsed = ptag[ptag.find('/>')+2:]
    
   
    return parsed


main()